<template>
  <div>
    <van-field
        v-model="areaName"
        input-align="right"
        :label="title"
        placeholder="请选择"
        :required="required"
        readonly
        clickable
        @click="show = true"
    />
    <van-popup v-model="show" position="bottom">
      <van-area title="请选择" :area-list="areaList" :columns-num="columnsNum" :value="value" @cancel="show=false" @confirm="getArea" />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from '@vant/area-data';
export default {
  props:{
    required: {
      type: Boolean,
      default: () => false,
    },
    areaId:{
      type: Array,
    },
    title:{
      type: String,
      default: () => '区域'
    },  
  },
  data(){
    return{
      areaList,
      areaName: null,
      value: null,
      columnsNum: 3,
      show: false,
    }
  },
  created(){
    this.init();
  },
  // watch:{
  //   areaId(newVal,oldVal){
  //     this.init();
  //   }
  // },
  methods:{
    async init(){
      let len = this.areaId.length;
      this.columnsNum = len;
      this.value = this.areaId[len-1];
      let area = [];
      if(this.areaId[0]){
        area[0] = await this.getName(0,0);
      }
      if(this.areaId[1]){
        area[1] = await this.getName(this.areaId[0],1);
      }
      if(this.areaId[2]){
        area[2] = await this.getName(this.areaId[1], 2);
      }
      this.areaName = area.join('/');
    },
    async getName(id, index){
      let res = await this.$http('get', '/common/area/'+id, {});
      let arr = res.rows.filter(item => item.id == this.areaId[index]);
      return new Promise((resolve, reject) => {
				resolve(arr[0].name);
			});
    },
    getArea(data){
      let arr = data.map(item => item.name);
      this.areaName = arr.join('/');
      this.$emit('confirm', data);
      this.show = false;
    }
  }
}
</script>

<style>

</style>  